//
//  File.swift
//  RESTAPI
//
//  Created by 赵康 on 2024/10/6.
//

import Foundation
import Vapor
import Fluent
import Queues
import QueuesRedisDriver

struct PublishJob: AsyncScheduledJob {
    func run(context: Queues.QueueContext) async throws {
        print("THIS FUNCTION IS INVOCKED EVERY SECOND")
        try await query(on: context.application.db)
    }
    
    @discardableResult
    func query(on db: Database) async throws -> HTTPStatus {
        let guides = try await GuideModel.query(on: db)
            .filter(\.$status == StatusEnum.planned.rawValue)
            .all()
        for i in guides {
            if i.publishedDate == Date() {
                i.status = StatusEnum.published.rawValue
                try await i.save(on: db)
            }
        }
        
        let articles = try await ArticleModel.query(on: db)
            .filter(\.$status == StatusEnum.planned.rawValue)
            .all()
        let currentDate = Calendar.current.startOfDay(for: Date())
        for i in articles {
            guard let publishedDate = i.publishedDate else { continue }
            
            let currentDate = Calendar.current.startOfDay(for: Date())
            if Calendar.current.isDate(publishedDate, inSameDayAs: currentDate) {
                i.status = StatusEnum.published.rawValue
                try await i.save(on: db)
            }
        }
        
        let courses = try await CourseModel.query(on: db)
            .filter(\.$status == StatusEnum.planned.rawValue)
            .all()
        for i in courses {
            if i.publishedDate == Date() {
                i.status = StatusEnum.published.rawValue
                try await i.save(on: db)
            }
        }
        
        let sessions = try await SessionModel.query(on: db)
            .filter(\.$status == StatusEnum.planned.rawValue)
            .all()
        for i in sessions{
            if i.publishedAt == Date() {
                i.status = StatusEnum.published.rawValue
                try await i.save(on: db)
            }
        }
        
        return .ok
    }
}
